package com.ir.stat.spark.client;

import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.filter.EncodingFilter;
import org.glassfish.jersey.message.GZipEncoder;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.List;

public class BaseClient {
    private Client client;
    private String baseUrl;
    private Response response;
    private int timeout = 60 * 1000 * 5;

    public BaseClient(String baseUrl) {
        this.client = ClientBuilder.newClient();
        client.property(ClientProperties.CONNECT_TIMEOUT, timeout);
        client.property(ClientProperties.READ_TIMEOUT, timeout);
        client.register(GZipEncoder.class);
        client.register(EncodingFilter.class);
        this.baseUrl = baseUrl;
    }

    protected WebTarget getResource(String url) {
        return client.target("http://" + baseUrl + "/api" + url);
    }

    protected void setResponse(Response response) {
        this.response = response;
    }

    public String getResponseText() {
        if (response != null) {
            if(response.getStatus() == 200) {
                return response.readEntity(String.class);
            }else{
                System.err.println("status: " + response.getStatus() + ", entity: " + response.readEntity(String.class));
            }
        }
        return null;
    }

    public String getAuthToken() {
        List<String> token = (List) response.getHeaders()
                .get("X-AUTH-TOKEN");
        return token == null ? null : token.get(0);
    }

    public void close() {
        if (client != null) {
            try {
                client.close();
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
    }
}
